from selenium import webdriver
from selenium import common
import time


class Searcher:
    My_Search_Website = ""
    Search_AT = ""
    Keys = []
    CSS_search = ""
    CSS_box = ""
    link_text = ""
    d = ""
    Out_Keys = [],
    Out_equal_keys = []
    Search_res = []
    name_set = []
    max_page_num = 10

    def __init__(
            self,
            My_Search_Website: str,
            Keys: list,
            CSS_search: str,
            CSS_box: str,
            link_text: str,
            Search_AT: str,
            driver: webdriver.Chrome,
            Out_Keys=[],
            Out_equal_keys=[],
            max_page_num=10

    ):
        self.Keys = Keys
        self.My_Search_Website = My_Search_Website
        self.CSS_box = CSS_box
        self.CSS_search = CSS_search
        self.link_text = link_text
        self.d = driver
        self.Out_Keys = Out_Keys
        self.Out_equal_keys = Out_equal_keys
        self.max_page_num = max_page_num
        self.Search_AT = Search_AT

    def write_name(self, filename="name.txt"):
        print("注意，现在运行的代码是测试内容，运行任务时你不应该看见我。")
        with open(filename, "w+", encoding="utf-8") as f:
            for i in self.name_set:
                print("正在写入：" + i[0] + " " + i[1] + "\n")
                f.write(i[0] + "\t" + i[1] + "\n")

    def keys_to_str(self, keys: list):
        r = ''
        for s in keys:
            r += (" " + str(s))
        return r

    def go_for_a_search_page(self):
        time.sleep(1)
        res = self.d.find_elements_by_css_selector(".t>a")
        if len(res) == 0:
            print("休息一下")
            time.sleep(5)
            res = self.d.find_elements_by_css_selector(".t>a")
        print(len(res))
        for r in res:
            is_append = True
            for ss in self.Out_Keys:  # 关键词屏蔽
                if str(r.text).find(ss) >= 0:
                    is_append = False
                    break
            for ss in self.Out_equal_keys:  # 全词匹配屏蔽
                if str(r.text) == ss:
                    is_append = False
                    break

            if is_append:
                self.Search_res.append(str(r.get_attribute("href")))
                self.name_set.append([str(r.text), str(r.get_attribute("href"))])
            else:
                print("标题:" + str(r.text) + " 是不符合要求的。")
                print("过滤1条内容")

    def go(self):
        print("现在将切换到 " + self.My_Search_Website + " 进行搜索。")
        self.d.get('https://www.baidu.com')
        self.d.find_element_by_css_selector(self.CSS_box).send_keys(
            self.keys_to_str(self.Keys) + " site:" + self.Search_AT)
        self.d.find_element_by_css_selector(self.CSS_search).click()
        page = 1

        while True:
            print("当前是第 " + str(page) + " 页的搜索内容.")
            self.go_for_a_search_page()
            print(self.Search_res)
            print("现在已经检索到 " + str(len(self.Search_res)) + " 条内容。")

            if page >= self.max_page_num:
                print("已达到设定的最大页数。")
                print("退出搜索")
                break
            time.sleep(0.5)
            s = self.d.find_elements_by_link_text(self.link_text)
            if len(s) == 1:
                page += 1
                try:
                    s[0].click()
                except common.exceptions.ElementClickInterceptedException:
                    print("发生了一个异常！！！重试中")
                    time.sleep(5)
                    s = self.d.find_elements_by_link_text(self.link_text)
                    if len(s) == 1:
                        page += 1
                        s[0].click()

                continue
            else:
                print("没有下一页了，现在退出.")
                break

        print(self.Search_res)
        return self.Search_res


#########################################################
class BaiduSearcher(Searcher):
    def __init__(
            self,
            Keys: list,
            driver: webdriver.Chrome,
            Search_AT: str,
            Out_Keys=[],
            Out_equal_keys=[],
            max_page_num=10
    ):
        super(BaiduSearcher, self).__init__(
            My_Search_Website="http://www.baidu.com",
            Keys=Keys,
            CSS_box="#kw",
            CSS_search="#su",
            driver=driver,
            Search_AT=Search_AT,
            link_text="下一页 >",
            Out_Keys=Out_Keys,
            Out_equal_keys=Out_equal_keys,
            max_page_num=max_page_num
        )


class M_WEIBO_CN_Searcher:
    Keys = []
    """
    Out_Keys = []
    Out_equal_keys = []"""
    max_search_res_num = 10
    d = None

    def __init__(
            self,
            Keys: list,
            driver: webdriver.Chrome,
            max_search_res_num=10
    ):
        self.Keys = Keys
        self.d = driver

    def keys_to_str(self, keys: list):
        r = ''
        for s in keys:
            r += (" " + str(s))
        return r


    def go(self):
        r = []
        print("现在将跳转到 m.weibo.cn 进行搜索")
        self.d.get("http://m.weibo.cn")
        time.sleep(1)
        f1 = self.d.find_elements_by_css_selector(".nav-search")
        if len(f1) == 0:
            print("SEARCH m.weibo.cn 在进入搜索页面时发生了错误！")
            return []
        f1[0].click()
        time.sleep(0.5)
        f1 = self.d.find_elements_by_tag_name("input")
        if len(f1) == 0:
            print("SEARCH m.weibo.cn 在点击搜索页面时发生了错误！")
            return []
        f1[0].send_keys(self.keys_to_str(keys=self.Keys))
        f1[0].send_keys('\n')#开始搜索

